package com.mytest.gateway.filter;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mytest.common.jwt.JwtUtil;
import com.mytest.gateway.config.FilterProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: WangZhongLiang
 * @Date: 2019/6/14
 */
@Slf4j
@EnableConfigurationProperties({FilterProperties.class})
@Component
public class GbFilter extends ZuulFilter {
    @Autowired
    private FilterProperties prop;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        System.out.println("11111111111111111");

        // 返回值：true代表拦截，false代表不拦截
        RequestContext ctx = null;
        String path = "";
        try {
            // 获取上下文
            ctx = RequestContext.getCurrentContext();
            // 获取request
            HttpServletRequest request = ctx.getRequest();
            // 获取当前请求路径，是没有域名端口号的，e.g ： /mytest/provider/service/user/mq
            path = request.getRequestURI();
            log.info("请求url：" + path);
            // 获取token
            String token1 = request.getHeader("accessToken");

            // 获取redis里的token
//            String token = (String)redisTemplate.opsForValue().get(token1);
//            log.info("token:"+token);

//            // 解析token
//            if (StringUtils.isEmpty(token) || "".equals(token.trim())) {
//                //有些地址禁止访问
//                ArrayList<String> list = Lists.newArrayList();
//                list.add("/retailStore/goods/app/goods/getGoodsDetailByIds");
//                list.add("/retailStore/order/app");
//                list.add("/gb/app");
//                for (String s : list) {
//                    if (path.startsWith(s)) {
//                        return true;
//                    }
//                }
//            }
//            Claims claims = JwtUtil.parseJwt(token);
//            String subject = claims.getSubject();
//            JSONObject jsonObject = JSONObject.parseObject(subject);
//            System.out.println("11111111111111"+jsonObject);
//            String userId = jsonObject.getString("id");
            //将转换后的数据放入请求参数中
//            Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();
//            if (requestQueryParams == null) requestQueryParams = new HashMap<>();
//            List<String> paramsList = new ArrayList<>();
//            paramsList.add(userId);
//            requestQueryParams.put("userId", paramsList);
//            ctx.setRequestQueryParams(requestQueryParams);
//            System.out.println("ppppppppppppppppppp :"+ctx);
        } catch (Exception e) {
            log.info("errorMsg：" + e.getMessage());
//            e.printStackTrace();
//            PrintWriter out = null;
//            try {
//                HttpServletResponse response = ctx.getResponse();
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("application/json");
//                out = response.getWriter();
//                out.println(JSON.toJSONString(ResultGenerator.genFailResult("token过期")));
//            } catch (Exception e1) {
//                e1.printStackTrace();
//            } finally {
//                if (out != null) {
//                    out.flush();
//                    out.close();
//                }
//            }
            return !isAllowPath(path);
        }
        System.out.println("11111111"+!isAllowPath(path));
        return !isAllowPath(path);
    }

    private boolean isAllowPath(String path) {
        // 获取所有放行的路径
        List<String> allowPaths = prop.getAllowPaths();
        // 判断
        for (String allowPath : allowPaths) {
            if (path.startsWith(allowPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run(){
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 获取token
        String token1 = request.getHeader("accessToken");
        if (StringUtils.isEmpty(token1) || "".equals(token1.trim())) {
            //让zuul过滤该请求
            ctx.setSendZuulResponse(false);
            //返回状态码
            ctx.setResponseStatusCode(401);
        }else {
            try {
                // 解析token
                String token = (String)redisTemplate.opsForValue().get(token1);

                Claims claims = JwtUtil.parseJwt(token);
                String subject = claims.getSubject();
                JSONObject jsonObject = JSONObject.parseObject(subject);
                String userId = jsonObject.getString("id");
                // 若session中不包含userId，则这次请求视为未登录请求，不给予路由，而提示“请登录”
                if (userId == null) {
                    ctx.setSendZuulResponse(false);
                    ctx.setResponseStatusCode(401);
                }

                /*// 获取redis里的token
                System.out.println("11111111111111"+jsonObject);
//        String userId = jsonObject.getString("id");
                String userIp = jsonObject.getString("ip");
                String[] split1 = userIp.split(",");
                userIp = split1[0];

                System.out.println("userIp::"+userIp);
                String ipAddress = getIpAddress(request);
                String[] split2 = ipAddress.split(",");
                ipAddress = split2[0];
                System.out.println("ipAddress::"+ipAddress);
                if (!userIp.equals(ipAddress)){
                    ctx.setSendZuulResponse(false);
                    ctx.setResponseStatusCode(401);
                }
                System.out.println("kkkkkkkkkkk");*/

            } catch (Exception e) {
                //token解析失败
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(403);
                e.printStackTrace();
            }
        }
        // TODO 根据用户信息，校验权限
        return null;
//        return "121";
    }

    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
